﻿using System;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;

namespace CivilRegistry.ControlledModel.Repository.Extensions
{
    /// <summary>
    /// The ObjectContext Extensions.
    /// </summary>
    public static class ObjectContextExtensions
    {

        /// <summary>
        /// To retrive the EntitySetName.
        /// </summary>
        /// <param name="context">The ObjectContext object.</param>
        /// <param name="entity">The EntityObject instance.</param>
        /// <returns>The EntitySetName.</returns>
        public static string GetEntitySetName(this ObjectContext context, EntityObject entity)
        {
            // If the EntityKey exists, simply get the Entity Set name from the key
            if (entity.EntityKey != null)
            {
                return entity.EntityKey.EntitySetName;
            }
            else
            {
                string entityTypeName = getEntityTypeName(entity.GetType());
                var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
                string entitySetName = (from meta in container.BaseEntitySets
                                        where meta.ElementType.Name == entityTypeName
                                        select meta.Name).First();

                return container.Name + "." + entitySetName;
            }
        }

        /// <summary>
        /// To retrive the EntityTypeName from a Type.
        /// </summary>
        /// <param name="type">The Type from which the name should be retrived.</param>
        /// <returns>The EntityTypeName.</returns>
        private static string getEntityTypeName(Type type)
        {
            if (type.FullName.StartsWith("CivilRegistry.ControlledModel."))
                return type.Name;
            else
                return getEntityTypeName(type.BaseType);
        }

    }
}